package jp.co.picture9918;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.repackaged.org.apache.commons.logging.Log;
import com.google.appengine.repackaged.org.apache.commons.logging.LogFactory;
import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.GphotoEntry;
import com.google.gdata.data.photos.UserFeed;

@SuppressWarnings("serial")
public class MyPacasaServlet extends HttpServlet {
	private static final Log log = LogFactory.getLog(MyPacasaServlet.class);

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		log.info("MyPacasaServlet Ben5");
		User user = null;
		try{
			UserService userService = UserServiceFactory.getUserService();
			user = userService.getCurrentUser();
			
			if(user == null){
				//String loginUrl = userService.createLoginURL(req.getRequestURL().toString());
				String loginUrl = userService.createLoginURL(req.getRequestURL().toString());
				resp.sendRedirect(loginUrl);
			}else{
				PicasawebService service = new PicasawebService("memroies-album");
				log.info(user);
				URL feedUrl = new URL("http://picasaweb.google.com/data/feed/api/user/" + user.getNickname() + "?kind=album");
				UserFeed myUserFeed = service.getFeed(feedUrl, UserFeed.class);
			    List<GphotoEntry> entries = myUserFeed.getEntries();
			    List<AlbumEntry> albumList = new ArrayList<AlbumEntry>();
			    AlbumEntry albumEntry = null;
			    for (GphotoEntry entry : entries) {
			        GphotoEntry adapted = entry.getAdaptedEntry();
			        if (adapted instanceof AlbumEntry) {
			        	albumEntry = (AlbumEntry)adapted;
			        	albumList.add(albumEntry);
			        	log.info("albumEntry : " + albumEntry.getTitle().getPlainText());
			        }
			    }
				resp.setContentType("text/plain");
				resp.getWriter().println("Hello, world");
			}
		}catch(Exception e){
			e.printStackTrace();
			log.error(e);
		}
	}
}
